package cn.rui.shiro.realms;

import cn.rui.pojo.Admins;
import cn.rui.service.AdminService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 自定义realm
 * @author 徽州大都督
 * @date 2020/8/11
 */
public class CustomerRealm extends AuthorizingRealm {

    @Autowired
    private AdminService adminService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        String primaryPrincipal = (String) principalCollection.getPrimaryPrincipal ();
        System.out.println ("当前操作用户:" + primaryPrincipal);
        //获取身份信息

        if (primaryPrincipal.equals ("admin")){
            List<String> permissions = new ArrayList<String> ();
            permissions.add("admin");
            // 将权限信息封闭为AuthorizationInfo
            SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
            for (String permission : permissions) {
                simpleAuthorizationInfo.addStringPermission(permission);
            }
            return simpleAuthorizationInfo;
        }

        //permissions.add("user:delete");





        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        String username= (String) token.getPrincipal ();


        System.out.println ("当前登陆用户:"+username);
        Admins admins = adminService.findByName (username);


        if (!ObjectUtils.isEmpty (admins)){
            return new SimpleAuthenticationInfo (admins.getAdminUsername (),admins.getAdminPassword (),ByteSource.Util.bytes (admins.getSalt ()),this.getName ());
        }
        return null;
    }
}
